package as3.carcassone.model {
	import as3.carcassone.GameConstants;
	import as3.carcassone.tiles.IGameTile;
	import as3.carcassone.view.GameBoard;
	import as3.carcassone.view.TilePicker;

	import nl.ypmits.Setup;

	import flash.events.Event;
	import flash.events.EventDispatcher;

	public class Model extends EventDispatcher {

		private static var _instance : Model;
		
		private var _tiles : Vector.<IGameTile>;
		private var _tilesOnBoard : Vector.<IGameTile>;
		private var _currentTile : IGameTile;
		private var _gameboard : GameBoard;
		private var _tilepicker : TilePicker;
		
		public static function get instance() : Model {
			if( _instance == null ) _instance = new Model( new SingletonEnforcer() );
			return _instance;
		}

		
		public function Model( enforcer : SingletonEnforcer ) {
			if( !enforcer ) trace( "ERROR: Model should not be instantiated with 'new'. Use it like: Model.instance.etcetera" );
			
		}



		public function createNewGame() : void
		{
			_tilesOnBoard = new Vector.<IGameTile>();
			
			_tiles = GameConstants.tiles.concat();
			_gameboard = new GameBoard();
			Setup.stage.addChild( _gameboard );
			
			_tilepicker = new TilePicker();
			_tilepicker.x = Setup.stage.stageWidth - _tilepicker.width;
			Setup.stage.addChild( _tilepicker );
		}



		public function get tiles() : Vector.<IGameTile>
		{
			return _tiles;
		}



		public function set tiles( tiles : Vector.<IGameTile> ) : void
		{
			_tiles = tiles;
		}
		
		
		
		public function pickRandomTile() : IGameTile
		{
			if ( Model.instance.tiles.length == 0)
			{
				return null;
			} else {
				var r : Number = int( Math.random( ) *  Model.instance.tiles.length );
				_currentTile = Model.instance.tiles[r];
				_tilesOnBoard.push( _currentTile );
				Model.instance.tiles.splice( r, 1 );
			}
			dispatchEvent( new Event( Event.CHANGE ) );
			return _currentTile;
		}



		public function get currentTile() : IGameTile
		{
			return _currentTile;
		}



		public function get gameboard() : GameBoard
		{
			return _gameboard;
		}


		public function get tilepicker() : TilePicker
		{
			return _tilepicker;
		}
	}
}
class SingletonEnforcer {}
